package com.spring.crm.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.spring.crm.conf.CommonResult;
import com.spring.crm.conf.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("api")
public class FileUpload {
    // 设置固定的日期格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    // 将 yml 中的自定义配置注入到这里
    @Value("${upload.path}")
    private String uploadPath;




    // 文件上传 （可以多文件上传）
    @CrossOrigin(origins = "*")
    @PostMapping("file/upload")
    public CommonResult fileUploads(@RequestParam("file") MultipartFile multiFile, @RequestParam Map<String,String> map) throws Exception {
        CommonResult rs;
        // 得到格式化后的日期
        String format = sdf.format(new Date());
        String myTimeFormat = timeFormat.format(new Date());
        // 获取上传的文件名称
        if (multiFile == null){
            return CommonResult.failed("文件不能为空！");
        }
        String multiFileName = multiFile.getOriginalFilename();
        if (StringUtils.isBlank(multiFileName)){
            return CommonResult.failed("文件名不能为空！");
        }
        String suffix = multiFileName.substring(multiFileName.lastIndexOf("."));
        String type = FileUtil.getFileType("",suffix);
        //默认存放文件路径
        String myFile = "attach";
        //富文本的放到fwb目录
        if(map.containsKey("uploadType")){
            myFile = map.get("uploadType");
        }
        //上传文件
        String path = FileUtil.uploadMultiFile(multiFile, uploadPath, myFile,multiFileName);
        return CommonResult.success(path);
    }

    @GetMapping("download")
    public CommonResult downloadFile(@RequestParam Map<String,String> map, HttpServletResponse response) {
        CommonResult rs;
        try {
            String fileName = uploadPath+map.get("paperName");
            File file = new File(fileName);
            if (file.exists()) {
                //response.setContentType("application/force-download");// 设置强制下载不打开
                //response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return CommonResult.success("下载成功");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }else{
                rs = CommonResult.failed("文件不存在！");
            }
            rs = CommonResult.success("下载成功");
        }catch(Exception ex){
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }
}
